function plot_iteration_convergence()
% GMCM 2025 迭代收敛曲线绘制脚本
% 专门处理每次迭代的V_stay记录
% 数据格式: Iteration,V_stay,Phase,Time_Seconds,Improvement_Flag,Description

fprintf('=== GMCM 2025 迭代收敛曲线分析工具 ===\n');

%% 1. 读取迭代收敛数据
data_file = 'result/Problem1/iteration_convergence.csv';
if ~exist(data_file, 'file')
    error('迭代收敛数据文件不存在: %s', data_file);
end

% 读取CSV数据
fprintf('正在读取数据文件: %s\n', data_file);
data = readtable(data_file);

% 提取数据列
iterations = data.Iteration;
vstay_values = data.V_stay;
phases = data.Phase;
times = data.Time_Seconds;
improvement_flags = data.Improvement_Flag;
descriptions = data.Description;

fprintf('成功读取 %d 个数据点\n', height(data));

%% 2. 数据分析
initial_vstay = vstay_values(1);
final_vstay = vstay_values(end);
total_improvement = (initial_vstay - final_vstay) / initial_vstay * 100;

% 分离Phase 1和Phase 2数据
phase1_idx = strcmp(phases, 'Phase1');
phase2_idx = strcmp(phases, 'Phase2');

phase1_iterations = iterations(phase1_idx);
phase1_vstay = vstay_values(phase1_idx);
phase1_times = times(phase1_idx);

phase2_iterations = iterations(phase2_idx);
phase2_vstay = vstay_values(phase2_idx);
phase2_times = times(phase2_idx);

% 统计改进次数
total_improvements = sum(improvement_flags);
phase1_improvements = sum(improvement_flags(phase1_idx));
phase2_improvements = sum(improvement_flags(phase2_idx));

fprintf('\n=== 收敛分析结果 ===\n');
fprintf('初始V_stay: %s\n', addCommas(initial_vstay));
fprintf('最终V_stay: %s\n', addCommas(final_vstay));
fprintf('总体改进: %.2f%%\n', total_improvement);
fprintf('总迭代次数: %d\n', max(iterations));
fprintf('总改进次数: %d (阶段一: %d, 阶段二: %d)\n', total_improvements, phase1_improvements, phase2_improvements);
if ~isempty(phase1_iterations)
    fprintf('阶段一迭代数: %d\n', length(phase1_iterations));
end
if ~isempty(phase2_iterations)
    fprintf('阶段二轮数: %d\n', length(phase2_iterations));
end

%% 3. 创建主收敛曲线图
figure('Position', [100, 100, 1600, 1200]);

% 主收敛曲线 (大图)
subplot(3,2,[1,2]);
hold on;

% 绘制完整的收敛轨迹
plot(iterations, vstay_values, 'b-', 'LineWidth', 1.5, 'DisplayName', '完整收敛轨迹');

% 标记改进点
improvement_idx = improvement_flags == 1;
if any(improvement_idx)
    scatter(iterations(improvement_idx), vstay_values(improvement_idx), 100, 'red', 'filled', ...
            'DisplayName', sprintf('改进点 (%d个)', sum(improvement_idx)));
end

% 分阶段着色
if any(phase1_idx)
    plot(phase1_iterations, phase1_vstay, 'r-', 'LineWidth', 2, 'DisplayName', '阶段一');
end
if any(phase2_idx)
    plot(phase2_iterations, phase2_vstay, 'g-', 'LineWidth', 2, 'DisplayName', '阶段二');
end

% 添加关键点标注
text(iterations(1), vstay_values(1), sprintf('  初始值\n  %s', addCommas(vstay_values(1))), ...
     'FontSize', 10, 'Color', 'red', 'FontWeight', 'bold');
text(iterations(end), vstay_values(end), sprintf('  最终值\n  %s', addCommas(vstay_values(end))), ...
     'FontSize', 10, 'Color', 'blue', 'FontWeight', 'bold');

% 添加阶段分界线
if any(phase1_idx) && any(phase2_idx)
    phase_boundary = max(phase1_iterations);
    xline(phase_boundary, '--', 'Color', [0.7 0.7 0.7], 'LineWidth', 1.5, 'DisplayName', '阶段分界');
end

title(sprintf('GMCM 2025 完整迭代收敛曲线\n总改进: %.2f%% (%s → %s)', ...
      total_improvement, addCommas(initial_vstay), addCommas(final_vstay)), ...
      'FontSize', 14, 'FontWeight', 'bold');
xlabel('迭代次数');
ylabel('V_{stay} 内存占用');
legend('Location', 'northeast');
grid on;
ytickformat('%,.0f');
hold off;

%% 4. 阶段一详细分析
if any(phase1_idx)
    subplot(3,2,3);
    hold on;
    plot(phase1_iterations, phase1_vstay, 'r-o', 'LineWidth', 2, 'MarkerSize', 4);
    
    % 标记阶段一的改进点
    phase1_improvement_idx = phase1_idx & improvement_flags == 1;
    if any(phase1_improvement_idx)
        scatter(iterations(phase1_improvement_idx), vstay_values(phase1_improvement_idx), 80, 'red', 'filled');
    end
    
    title(sprintf('阶段一详细收敛 (%d次迭代, %d次改进)', length(phase1_iterations), phase1_improvements));
    xlabel('迭代次数');
    ylabel('V_{stay}');
    grid on;
    ytickformat('%,.0f');
    hold off;
end

%% 5. 阶段二详细分析
if any(phase2_idx)
    subplot(3,2,4);
    hold on;
    plot(phase2_iterations, phase2_vstay, 'g-o', 'LineWidth', 2, 'MarkerSize', 6);
    
    % 标记阶段二的改进点
    phase2_improvement_idx = phase2_idx & improvement_flags == 1;
    if any(phase2_improvement_idx)
        scatter(iterations(phase2_improvement_idx), vstay_values(phase2_improvement_idx), 80, 'red', 'filled');
    end
    
    title(sprintf('阶段二详细收敛 (%d轮, %d次改进)', length(phase2_iterations), phase2_improvements));
    xlabel('轮次');
    ylabel('V_{stay}');
    grid on;
    ytickformat('%,.0f');
    hold off;
end

%% 6. 时间收敛分析
subplot(3,2,5);
plot(times/60, vstay_values, 'b-o', 'LineWidth', 2, 'MarkerSize', 4);
title('时间 vs V_{stay}');
xlabel('时间 (分钟)');
ylabel('V_{stay}');
grid on;
ytickformat('%,.0f');

%% 7. 改进分布分析
subplot(3,2,6);
if any(improvement_idx)
    improvement_vstay = vstay_values(improvement_idx);
    improvement_iters = iterations(improvement_idx);
    
    % 计算每次改进的幅度
    improvement_amounts = zeros(size(improvement_vstay));
    for i = 1:length(improvement_vstay)
        if i == 1
            improvement_amounts(i) = initial_vstay - improvement_vstay(i);
        else
            improvement_amounts(i) = improvement_vstay(i-1) - improvement_vstay(i);
        end
    end
    
    bar(improvement_iters, improvement_amounts, 'FaceColor', [0.3 0.6 0.9]);
    title(sprintf('改进分布 (共%d次改进)', length(improvement_amounts)));
    xlabel('迭代次数');
    ylabel('改进幅度');
    grid on;
else
    text(0.5, 0.5, '未发现改进', 'HorizontalAlignment', 'center', 'FontSize', 14);
    title('改进分布');
end

%% 8. 保存结果
output_dir = 'result/Problem1';
if ~exist(output_dir, 'dir')
    mkdir(output_dir);
end

% 保存图像
saveas(gcf, fullfile(output_dir, 'Conv_Case0_iteration_convergence.png'));
saveas(gcf, fullfile(output_dir, 'Conv_Case0_iteration_convergence.fig'));

% 生成详细统计报告
report_file = fullfile(output_dir, 'Conv_Case0_iteration_report.txt');
fid = fopen(report_file, 'w');
fprintf(fid, '=== GMCM 2025 迭代收敛分析报告 ===\n');
fprintf(fid, '生成时间: %s\n', datestr(now));
fprintf(fid, '数据文件: %s\n\n', data_file);

fprintf(fid, '=== 总体统计 ===\n');
fprintf(fid, '初始V_stay: %s\n', addCommas(initial_vstay));
fprintf(fid, '最终V_stay: %s\n', addCommas(final_vstay));
fprintf(fid, '总体改进: %.2f%%\n', total_improvement);
fprintf(fid, '总运行时间: %.2f 分钟\n', times(end)/60);
fprintf(fid, '总迭代次数: %d\n', max(iterations));
fprintf(fid, '总改进次数: %d\n\n', total_improvements);

fprintf(fid, '=== 分阶段统计 ===\n');
if any(phase1_idx)
    fprintf(fid, '阶段一:\n');
    fprintf(fid, '  迭代次数: %d\n', length(phase1_iterations));
    fprintf(fid, '  改进次数: %d\n', phase1_improvements);
    fprintf(fid, '  起始V_stay: %s\n', addCommas(phase1_vstay(1)));
    fprintf(fid, '  结束V_stay: %s\n', addCommas(phase1_vstay(end)));
    phase1_improvement = (phase1_vstay(1) - phase1_vstay(end)) / phase1_vstay(1) * 100;
    fprintf(fid, '  阶段改进: %.2f%%\n\n', phase1_improvement);
end

if any(phase2_idx)
    fprintf(fid, '阶段二:\n');
    fprintf(fid, '  轮数: %d\n', length(phase2_iterations));
    fprintf(fid, '  改进次数: %d\n', phase2_improvements);
    fprintf(fid, '  起始V_stay: %s\n', addCommas(phase2_vstay(1)));
    fprintf(fid, '  结束V_stay: %s\n', addCommas(phase2_vstay(end)));
    if length(phase2_vstay) > 1
        phase2_improvement = (phase2_vstay(1) - phase2_vstay(end)) / phase2_vstay(1) * 100;
        fprintf(fid, '  阶段改进: %.2f%%\n\n', phase2_improvement);
    end
end

fprintf(fid, '=== 改进点详情 ===\n');
improvement_details = data(improvement_idx, :);
for i = 1:height(improvement_details)
    fprintf(fid, '迭代 %d: %s (%s)\n', improvement_details.Iteration(i), ...
            addCommas(improvement_details.V_stay(i)), improvement_details.Description{i});
end

fclose(fid);

% 保存处理后的数据
processed_data_file = fullfile(output_dir, 'processed_convergence_data.mat');
save(processed_data_file, 'iterations', 'vstay_values', 'phases', 'times', 'improvement_flags', ...
     'total_improvement', 'phase1_improvements', 'phase2_improvements');

fprintf('\n=== 输出文件 ===\n');
fprintf('收敛曲线图: %s\n', fullfile(output_dir, 'Conv_Case0_iteration_convergence.png'));
fprintf('MATLAB图文件: %s\n', fullfile(output_dir, 'Conv_Case0_iteration_convergence.fig'));
fprintf('详细报告: %s\n', report_file);
fprintf('处理后数据: %s\n', processed_data_file);
fprintf('\n✅ 迭代收敛曲线分析完成！\n');

end

function str = addCommas(num)
% 为数字添加千位分隔符
str = sprintf('%,.0f', num);
end

